"""
商品列表页面

显示和管理所有商品的页面
"""

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from pathlib import Path
import sys

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame, 
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class ProductListPage(BasePage):
    """商品列表页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.products = []  # 商品数据
        self.filtered_products = []  # 过滤后的商品
        self.current_filter = "all"
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 工具栏
        self.create_toolbar()
        
        # 商品列表
        self.create_product_list()
        
        # 加载示例数据
        self.load_sample_data()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)
        
        title_label = ttk.Label(
            title_container,
            text="📦 商品列表",
            style='Title.TLabel'
        )
        title_label.pack(side="left")
        
        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="查看和管理所有商品信息",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))
        
        # 操作按钮区域
        action_frame = ttk.Frame(header_frame)
        action_frame.pack(side="right")
        
        # 刷新按钮
        refresh_btn = create_secondary_button(
            action_frame,
            text="🔄 刷新",
            command=self.refresh_products
        )
        refresh_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))
    
    def create_toolbar(self):
        """创建工具栏"""
        toolbar_frame = create_card_frame(self.frame, "筛选和操作")
        toolbar_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))
        
        # 第一行：筛选控件
        filter_row = ttk.Frame(toolbar_frame)
        filter_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))
        
        # 分类筛选
        category_container = ttk.Frame(filter_row)
        category_container.pack(side="left")
        
        ttk.Label(category_container, text="分类筛选:", style='Heading.TLabel').pack(side="left")
        
        self.category_filter_var = tk.StringVar(value="all")
        category_combo = ttk.Combobox(
            category_container,
            textvariable=self.category_filter_var,
            values=["all", "👕 服装", "👟 鞋类", "👜 包包", "💄 美妆", "📱 数码", "🏠 家居"],
            state="readonly",
            width=12
        )
        category_combo.pack(side="left", padx=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['lg']))
        category_combo.bind("<<ComboboxSelected>>", self.on_filter_changed)
        
        # 状态筛选
        status_container = ttk.Frame(filter_row)
        status_container.pack(side="left")
        
        ttk.Label(status_container, text="状态筛选:", style='Heading.TLabel').pack(side="left")
        
        self.status_filter_var = tk.StringVar(value="all")
        status_combo = ttk.Combobox(
            status_container,
            textvariable=self.status_filter_var,
            values=["all", "✅ 上架", "📦 备货中", "⏸️ 下架", "🔒 停产"],
            state="readonly",
            width=12
        )
        status_combo.pack(side="left", padx=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['lg']))
        status_combo.bind("<<ComboboxSelected>>", self.on_filter_changed)
        
        # 搜索框
        search_container = ttk.Frame(filter_row)
        search_container.pack(side="right")
        
        ttk.Label(search_container, text="搜索:", style='Heading.TLabel').pack(side="left")
        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(search_container, textvariable=self.search_var, width=25)
        search_entry.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))
        search_entry.bind("<KeyRelease>", self.on_search_changed)
        
        # 第二行：操作按钮
        action_row = ttk.Frame(toolbar_frame)
        action_row.pack(fill="x")
        
        # 左侧按钮组
        left_actions = ttk.Frame(action_row)
        left_actions.pack(side="left")
        
        add_btn = create_primary_button(
            left_actions,
            text="➕ 添加商品",
            command=self.add_product
        )
        add_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))
        
        import_btn = create_secondary_button(
            left_actions,
            text="📥 批量导入",
            command=self.import_products
        )
        import_btn.pack(side="left")
        
        # 右侧按钮组
        right_actions = ttk.Frame(action_row)
        right_actions.pack(side="right")
        
        export_btn = create_secondary_button(
            right_actions,
            text="📤 导出列表",
            command=self.export_list
        )
        export_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))
        
        delete_btn = create_danger_button(
            right_actions,
            text="🗑️ 删除选中",
            command=self.delete_selected
        )
        delete_btn.pack(side="right")
    
    def create_product_list(self):
        """创建商品列表"""
        list_frame = create_card_frame(self.frame, "商品列表")
        list_frame.pack(fill="both", expand=True)
        
        # 列表容器
        list_container = ttk.Frame(list_frame)
        list_container.pack(fill="both", expand=True)
        
        # 创建Treeview
        columns = ('sku', 'name', 'category', 'brand', 'price', 'status', 'created')
        self.product_tree = ttk.Treeview(list_container, columns=columns, show='headings', height=15)
        
        # 设置列标题和宽度
        column_config = {
            'sku': ('🏷️ SKU', 120),
            'name': ('📦 商品名称', 200),
            'category': ('🏪 分类', 100),
            'brand': ('🏢 品牌', 120),
            'price': ('💰 价格', 100),
            'status': ('🔄 状态', 100),
            'created': ('📅 创建时间', 150)
        }
        
        for col, (title, width) in column_config.items():
            self.product_tree.heading(col, text=title)
            self.product_tree.column(col, width=width, anchor='center' if col != 'name' else 'w')
        
        # 滚动条
        v_scrollbar = ttk.Scrollbar(list_container, orient="vertical", command=self.product_tree.yview)
        h_scrollbar = ttk.Scrollbar(list_container, orient="horizontal", command=self.product_tree.xview)
        self.product_tree.configure(yscrollcommand=v_scrollbar.set, xscrollcommand=h_scrollbar.set)
        
        # 布局
        self.product_tree.grid(row=0, column=0, sticky="nsew")
        v_scrollbar.grid(row=0, column=1, sticky="ns")
        h_scrollbar.grid(row=1, column=0, sticky="ew")
        
        list_container.grid_rowconfigure(0, weight=1)
        list_container.grid_columnconfigure(0, weight=1)
        
        # 绑定事件
        self.product_tree.bind("<Double-1>", self.on_item_double_click)
        self.product_tree.bind("<Button-3>", self.show_context_menu)
        
        # 添加空状态提示
        self.create_empty_state(list_frame)
    
    def create_empty_state(self, parent):
        """创建空状态提示"""
        self.empty_frame = ttk.Frame(parent)
        
        empty_icon = ttk.Label(
            self.empty_frame,
            text="📦",
            font=(DesignSystem.FONTS['family_primary'], 48)
        )
        empty_icon.pack(pady=(50, DesignSystem.SPACING['lg']))
        
        empty_title = ttk.Label(
            self.empty_frame,
            text="暂无商品",
            style='Heading.TLabel'
        )
        empty_title.pack()
        
        empty_desc = ttk.Label(
            self.empty_frame,
            text="点击「添加商品」按钮创建您的第一个商品",
            style='Muted.TLabel'
        )
        empty_desc.pack(pady=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['xl']))
        
        add_first_btn = create_primary_button(
            self.empty_frame,
            text="➕ 添加第一个商品",
            command=self.add_product
        )
        add_first_btn.pack()
    
    def load_sample_data(self):
        """加载示例数据"""
        sample_products = [
            {
                'sku': 'SKU001',
                'name': '时尚休闲T恤',
                'category': '👕 服装',
                'brand': 'Fashion Brand',
                'price': '¥99.00',
                'status': '✅ 上架',
                'created': '2024-01-15'
            },
            {
                'sku': 'SKU002',
                'name': '运动跑步鞋',
                'category': '👟 鞋类',
                'brand': 'Sport Brand',
                'price': '¥299.00',
                'status': '✅ 上架',
                'created': '2024-01-14'
            },
            {
                'sku': 'SKU003',
                'name': '商务手提包',
                'category': '👜 包包',
                'brand': 'Business Brand',
                'price': '¥199.00',
                'status': '📦 备货中',
                'created': '2024-01-13'
            },
            {
                'sku': 'SKU004',
                'name': '保湿面霜',
                'category': '💄 美妆',
                'brand': 'Beauty Brand',
                'price': '¥159.00',
                'status': '✅ 上架',
                'created': '2024-01-12'
            },
            {
                'sku': 'SKU005',
                'name': '无线蓝牙耳机',
                'category': '📱 数码',
                'brand': 'Tech Brand',
                'price': '¥399.00',
                'status': '⏸️ 下架',
                'created': '2024-01-11'
            }
        ]
        
        self.products = sample_products
        self.filtered_products = sample_products.copy()
        self.update_product_list()
    
    def update_product_list(self):
        """更新商品列表显示"""
        # 清空现有项目
        for item in self.product_tree.get_children():
            self.product_tree.delete(item)
        
        # 隐藏/显示空状态提示
        if self.filtered_products:
            self.empty_frame.pack_forget()
        else:
            self.empty_frame.place(relx=0.5, rely=0.5, anchor="center")
            return
        
        # 添加商品项目
        for product in self.filtered_products:
            # 根据状态设置标签
            status_tags = {
                '✅ 上架': 'active',
                '📦 备货中': 'preparing',
                '⏸️ 下架': 'inactive',
                '🔒 停产': 'discontinued'
            }
            tag = status_tags.get(product['status'], '')
            
            self.product_tree.insert('', 'end', values=(
                product['sku'],
                product['name'],
                product['category'],
                product['brand'],
                product['price'],
                product['status'],
                product['created']
            ), tags=(tag,))
        
        # 配置标签颜色
        self.product_tree.tag_configure('active', background=DesignSystem.COLORS['success_bg'])
        self.product_tree.tag_configure('preparing', background=DesignSystem.COLORS['warning_bg'])
        self.product_tree.tag_configure('inactive', background=DesignSystem.COLORS['gray_100'])
        self.product_tree.tag_configure('discontinued', background=DesignSystem.COLORS['danger_bg'])
    
    def on_filter_changed(self, event=None):
        """筛选条件改变"""
        self.apply_filters()
    
    def on_search_changed(self, event=None):
        """搜索条件改变"""
        self.apply_filters()
    
    def apply_filters(self):
        """应用筛选条件"""
        category_filter = self.category_filter_var.get()
        status_filter = self.status_filter_var.get()
        search_text = self.search_var.get().lower()
        
        self.filtered_products = []
        
        for product in self.products:
            # 分类筛选
            if category_filter != "all" and product['category'] != category_filter:
                continue
            
            # 状态筛选
            if status_filter != "all" and product['status'] != status_filter:
                continue
            
            # 搜索筛选
            if search_text and search_text not in product['name'].lower() and search_text not in product['sku'].lower():
                continue
            
            self.filtered_products.append(product)
        
        self.update_product_list()
    
    def on_item_double_click(self, event):
        """双击项目事件"""
        selection = self.product_tree.selection()
        if selection:
            item = self.product_tree.item(selection[0])
            product_name = item['values'][1]
            messagebox.showinfo("商品详情", f"查看商品: {product_name}")
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        item = self.product_tree.identify_row(event.y)
        if item:
            self.product_tree.selection_set(item)
            
            context_menu = tk.Menu(self.frame, tearoff=0)
            context_menu.add_command(label="查看详情", command=self.view_details)
            context_menu.add_command(label="编辑商品", command=self.edit_product)
            context_menu.add_separator()
            context_menu.add_command(label="查看素材", command=self.view_materials)
            context_menu.add_command(label="复制商品", command=self.copy_product)
            context_menu.add_separator()
            context_menu.add_command(label="删除商品", command=self.delete_product)
            
            context_menu.tk_popup(event.x_root, event.y_root)
    
    def add_product(self):
        """添加商品"""
        self.app.show_page("add_product")
    
    def import_products(self):
        """批量导入商品"""
        messagebox.showinfo("提示", "批量导入功能开发中...")
    
    def export_list(self):
        """导出商品列表"""
        file_path = filedialog.asksaveasfilename(
            title="导出商品列表",
            defaultextension=".csv",
            filetypes=[("CSV文件", "*.csv"), ("Excel文件", "*.xlsx")]
        )
        if file_path:
            messagebox.showinfo("成功", f"商品列表已导出到: {file_path}")
    
    def delete_selected(self):
        """删除选中的商品"""
        selection = self.product_tree.selection()
        if not selection:
            messagebox.showwarning("提示", "请先选择要删除的商品")
            return
        
        if messagebox.askyesno("确认删除", f"确定要删除选中的 {len(selection)} 个商品吗？"):
            for item in selection:
                self.product_tree.delete(item)
            messagebox.showinfo("成功", "商品删除成功")
    
    def view_details(self):
        """查看商品详情"""
        messagebox.showinfo("提示", "查看详情功能开发中...")
    
    def edit_product(self):
        """编辑商品"""
        messagebox.showinfo("提示", "编辑功能开发中...")
    
    def view_materials(self):
        """查看商品素材"""
        messagebox.showinfo("提示", "即将跳转到素材列表页面...")
        self.app.show_page("material_list")
    
    def copy_product(self):
        """复制商品"""
        messagebox.showinfo("提示", "复制商品功能开发中...")
    
    def delete_product(self):
        """删除单个商品"""
        if messagebox.askyesno("确认删除", "确定要删除这个商品吗？"):
            selection = self.product_tree.selection()
            if selection:
                self.product_tree.delete(selection[0])
                messagebox.showinfo("成功", "商品删除成功")
    
    def refresh_products(self):
        """刷新商品列表"""
        self.load_sample_data()
        messagebox.showinfo("成功", "商品列表已刷新")
